const _ = require('lodash');
const uuidv4 = require('uuid/v4');
const fs=require('fs');
const foodItemModel = require('../../app/models/foodItems.json');

module.exports = {
    getFoodItemByName : getFoodItemByName,
    getFoodItemByProducer: getFoodItemByProducer,
    getFoodList: getFoodList,
    getFoodItemByNameAndProducer: getFoodItemByNameAndProducer,
    deleteFoodItemByItemId: deleteFoodItemByItemId,
    addFootItem: addFootItem
}

function getFoodItemByName(name, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(name, item.name)) {
            result = item;
        }
    })
    callback(null, result);
}

function getFoodItemByProducer(producer, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(producer, item.producer)) {
            result = item;
        }
    })
    callback(null, result);
}

function getFoodList(callback) {
    let result = [];
    _.forEach(foodItemModel, (item) => {
        result.push(item)
    })
    callback(null,result);
}

function getFoodItemByNameAndProducer(name,producer, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(producer, item.producer) && _.isEqual(name, item.name)) {
            result = item;
        }
    })
    callback(null, result);
}

function deleteFoodItemByItemId(itemId,callback) {
    console.log(itemId)
    let delIndex;
    _.forEach(foodItemModel, (item,index) => {
        if (_.isEqual(itemId, item.itemId)) {
            delIndex=index;
        }
    })

    foodItemModel.splice(delIndex,1);

    var jsonString = JSON.stringify(foodItemModel, null, 4);
    fs.writeFile("./app/models/foodItems.json", jsonString, (err) => {
        if (err) throw err;
        console.log('delete success!');
    });

    callback(null, true);
}

function addFootItem(item, callback) {
    item.itemId=uuidv4();
    foodItemModel.push(item);
    
    var jsonString = JSON.stringify(foodItemModel, null, 4);
    fs.writeFile("./app/models/foodItems.json", jsonString, (err) => {
        if (err) throw err;
        console.log('add success!');
    });

    callback(null, true);
}